package com.huai.jt1078.handler.thread;

import cn.hutool.core.util.ObjectUtil;
import com.huai.jt1078.utils.SessionManager;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;

import java.util.LinkedList;
import java.util.concurrent.TimeUnit;

/**
 * @author xingkong
 * @program jt1078
 * @description 获取信息线程 - 守护线程
 * @date 2021-09-08 20:15
 **/
@Slf4j
public class TakeThread extends Thread{

    private final Object lock;
    private final LinkedList<byte[]> messages;
    private ChannelHandlerContext ctx = null;

    public TakeThread(Object lock, String tag, LinkedList<byte[]> messages) {
        String tempTag = null;
        this.lock = lock;
        this.messages = messages;
        int wait_number = 0;
        while (null == ctx){
            try {
                TimeUnit.MILLISECONDS.sleep(100);
            }catch (Exception e){
                e.printStackTrace();
            }
            wait_number++;
            if (wait_number > 100){
                throw new RuntimeException("不等了，中断这次等待");
            }
            ctx = SessionManager.instance.getTargetTagChannelMap().get(tag);
        }

    }

    @Override
    public void run() {
        log.info("---------启动拉取线程成功--------");
        // 当前线程不是中断状态
        while (!this.isInterrupted()){
            byte[] data = take();
            if (ObjectUtil.isNotNull(data) && data.length > 0){
                send(data);
            }

        }
    }

    private byte[] take() {
        byte[] data = null;
        try {
            synchronized (lock) {
                while (messages.isEmpty()) {
                    lock.wait(100);
                    if (this.isInterrupted()) {
                        return null;
                    }
                }
                data = messages.removeFirst();
            }
            return data;
        }catch(Exception ex) {
            return null;
        }
    }

    public void send(byte[] message) {
        try {
            ctx.writeAndFlush(message).await().await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
